﻿#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      P. Sanchez, M. Carrere
#
# Created:     28/05/2011
# Copyright:   (c) BDI 2011
# Licence:     GNU
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import matplotlib
from matplotlib.pyplot import axes
from matplotlib.pyplot import clf
from matplotlib.pyplot import close
from matplotlib.pyplot import figure
from matplotlib.pyplot import grid
from matplotlib.pyplot import plot
from matplotlib.pyplot import savefig
from matplotlib.pyplot import show
from matplotlib.pyplot import subplot
from matplotlib.pyplot import title
from matplotlib.pyplot import xlabel
from matplotlib.pyplot import ylabel
from matplotlib.pyplot import imshow
from matplotlib.pyplot import subplots_adjust
from matplotlib.pyplot import  rc
import numpy as np
#import pylab as plt
import matplotlib as plt
import scipy as sc
from numpy import sin
from scipy import pi
import os.path

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('multipage.pdf')

from modreststate import *

import guidata.dataset.datatypes as dt
import guidata.dataset.dataitems as di

from guidata.dataset.datatypes import DataSet, BeginGroup, EndGroup
from guidata.dataset.dataitems import (FloatItem, IntItem, BoolItem, ChoiceItem,
                             MultipleChoiceItem, ImageChoiceItem, FilesOpenItem,
                             StringItem, TextItem, ColorItem, FileSaveItem,
                             FileOpenItem, DirectoryItem, FloatArrayItem,
                             DateItem, DateTimeItem)
import tempfile
TEMPDIR = tempfile.mkdtemp(prefix="tmp_")
FILE_MAT = tempfile.NamedTemporaryFile(suffix=".mat", dir=".")

matplotlib.rc('text', usetex=False) # True= postscript
matplotlib.rc('font',**{'family':'serif','serif':['Times']})
matplotlib.rc('xtick', labelsize=9)
matplotlib.rc('ytick', labelsize=9)
matplotlib.rc('lines', linewidth=0.5)
matplotlib.rc('lines', color="r")



class FileParameter(dt.DataSet):
    """Selection fichier Matlab"""
    fnames = FilesOpenItem("Open files", "mat", FILE_MAT.name)

class DataParameter(dt.DataSet):
    """Parametres"""
    ThresholdBeforeTMS = di.IntItem("Threshold before TMS [ms]", min=1, max=100, default=10)
    ThresholdAfterTMS = di.IntItem("Threshold after TMS [ms]", min=1, max=100, default=20)
    deltaBeforeTMS = di.IntItem("delta before TMS [ms]", min=1, max=2000, default=300)
    deltaAfterTMS = di.IntItem("delta after TMS [ms]", min=1, max=2000, default=1200)
    tiBeforeTMS = di.IntItem("Analyse time [ms]", min=1, max=2000, default=150)
    nbptFFT= di.IntItem("Nb. point FFT", min=512, max=8192, default=2048)
    imageName=di.StringItem("Nom du fichier image",default="bloc")


class ChannelParameter(dt.DataSet):
    """Channel Parametres"""
    channel= di.IntItem("Channel", min=0, max=63, default=17)
    alphafilter=di.BoolItem("Filtre alpha",default=True)
    AlphaMin = di.FloatItem("Freq. min. [Hz]", min=1.0, max=1000.0, default=8.0)
    AlphaMax = di.FloatItem("Freq. max. [Hz]", min=1.0, max=1000.0, default=14.0)
    Fcsort = di.FloatItem("Freq. sorting [Hz]", min=1.0, max=1000.0, default=10.0)

import guidata
#-----------------------------------------------------------------------------
#        programme principal
#-----------------------------------------------------------------------------
if __name__ == '__main__':
    app = guidata.qapplication()
#-----------------------------------------------------------------------------
#    selection du fichier matlab .MAT
#-----------------------------------------------------------------------------
    f = FileParameter()
    if f.edit():
        filename=list(f.fnames)
        filename=filename[0]
        nouveau_nom = '.'.join(filename.split('.')[:-1])
        s=str(nouveau_nom)
        s=s.split("\\")
        N=len(s)
        nouveau_nom = s[N-1]
    else:
        exit(1)   # pas de fichier selectionne
#-----------------------------------------------------------------------------
#    lecture des donnees brutes
#-----------------------------------------------------------------------------
    nbchannel,nbblock,blocksize,voies,srate, dt=mat2pydata(filename)
    nbblock=int(nbblock)
    blocksize=int(blocksize)
    print " 1 bnb channel=", nbchannel,"nb block=", nbblock, "bock size=", blocksize

#-----------------------------------------------------------------------------
#   axe  des temps TMS au centre
#-----------------------------------------------------------------------------
    temps=CreatTimeTMS(blocksize,srate)
    t_sav=temps                          # sauvegarde axe des temps
#-----------------------------------------------------------------------------
#   Selection des intervalles d etude
#-----------------------------------------------------------------------------
    p= DataParameter()
    if p.edit():
        ThresholdBeforeTMS=p.ThresholdBeforeTMS*1e-3
        deltaBeforeTMS=p.deltaBeforeTMS*1e-3
        deltaAfterTMS=p.deltaAfterTMS*1e-3
        ThresholdAfterTMS=p.ThresholdAfterTMS*1e-3
        ti=p.tiBeforeTMS*1e-3
        nbptFFT=p.nbptFFT
    else:
        exit(2)
#-----------------------------------------------------------------------------
#      parametre selection de la voie
#-----------------------------------------------------------------------------
    c=ChannelParameter()
    if c.edit():
        numv=c.channel
        fc=c.Fcsort
    else:
        exit(3)
    numvoie=numv-1
    v=voies[numvoie,:,:]  # recupere la voie a etudier
    v=v.transpose()
    vsav=v.copy()       # sauvegarde de la voie origine
#-----------------------------------------------------------------------------
#     visualisation des blocs selectionnes - signal temporel
#-----------------------------------------------------------------------------
    v=raz_artefact(temps,v,ThresholdBeforeTMS,ThresholdAfterTMS,srate) # supprime artefact
    figure(1)
    Z=sinogramme(v)
    plot(temps,Z)
    title("Blocks signals without artefact",fontsize=9)
    xlabel("Time [s]")
    ylabel("Blocks")
    figure(2)
    imshow(v.transpose(),
                            interpolation='nearest',
                            extent=(0, blocksize, 0, nbblock),
                            origin ='lower' ,
                            aspect = 'normal')
    title("Blocks signals without artefact - above vue",fontsize=9)
    xlabel("Samples")
    ylabel("Blocks")
    show()
#-----------------------------------------------------------------------------
#     selection block avant TMS
#-----------------------------------------------------------------------------
    M_b,t_b, ind0_b, ind1_b, t0_b, t1_b=BlockBeforeTMS(v,blocksize,srate,temps,ThresholdBeforeTMS,deltaBeforeTMS)
    M_a,t_a, ind0_a, ind1_a, t0_a, t1_a=BlockAfterTMS(v,blocksize,srate,temps,ThresholdAfterTMS,deltaAfterTMS)

    figure(num=3, figsize=(8.27, 11.69), dpi=100)
    subplot(421)
    m,n=M_b.shape
    tmin=np.min(t_b)
    tsup=np.max(t_b)
    imshow(M_b.transpose(),
                            interpolation='nearest',
                            extent=(tmin,tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title("Blocks signals before TMS - above vue",fontsize=9)
    ylabel("Blocks")

    subplot(422)
    m,n=M_a.shape
    tmin=np.min(t_a)
    tsup=np.max(t_a)
    imshow(M_a.transpose(),
                            interpolation='nearest',
                            extent=(tmin,tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title("Blocks signals after TMS - above vue",fontsize=9)
    ylabel("Blocks")
    show()

#-----------------------------------------------------------------------------
#   calcul of crosscorrelation(after)
#-----------------------------------------------------------------------------
##    M_corr=[]
##    M_corr=correlationM_Ref( voies,
##                     2500,
##                     20,
##                     blocksize,srate,temps,ThresholdAfterTMS,deltaAfterTMS,
##                     dt,#scale for time
##                     nbchannel, #number of channels
##                     nbblock)
##    figure(7)
##    for i in range(nbchannel):
##        v=M_corr[i,:,:]  # recupere la voie a etudier
##        v=v.transpose()
##        plot(v)
##        show()

#-----------------------------------------------------------------------------
#   calcul of propagation (after) versus a reference electrode
#-----------------------------------------------------------------------------



#-----------------------------------------------------------------------------
#     calcul of filter's coefficients
#-----------------------------------------------------------------------------
    AlphaMin=c.AlphaMin
    AlphaMax=c.AlphaMax
    if c.alphafilter:
        bn=coefPassBand(AlphaMin, AlphaMax, srate)
#-----------------------------------------------------------------------------
#            beguinning of wavelets
#-----------------------------------------------------------------------------
    f_start=5.
    f_stop=50.
    deltafreq = 0.5
    sampling_rate = 2500.
    sizet_b=len(t_b)
    sizet_a=len(t_a)
    duree_b=sizet_b/sampling_rate
    duree_a=sizet_a/sampling_rate
    f0=2.
    scales = f0/np.arange(f_start,f_stop,deltafreq)*sampling_rate
    U=len(scales)
    V_b= sizet_b
    V_a= sizet_a
    WSUM_b=np.zeros((U, V_b), dtype=np.float)
    WSUM_a=np.zeros((U, V_a), dtype=np.float)
#-----------------------------------------------------------------------------
#  start of the loop over all blocs
#-----------------------------------------------------------------------------
    reference_phi_block=[]
    reference_mod_block=[]
    valeur_sup=[]
    reference_phi_block_a=[]
    reference_mod_block_a=[]
    valeur_sup_a=[]
    for loop in range(nbblock):
#-----------------------------------------------------------------------------
#   un block de la voie selectionnée
#-----------------------------------------------------------------------------
        signal_b=M_b[:,loop]
        signal_a=M_a[:,loop]
#-----------------------------------------------------------------------------
#   selection filtre
#-----------------------------------------------------------------------------
        if c.alphafilter:
           filtered_b = []
           filtered_b.append(sc.convolve(bn, signal_b)) # filter the signal by convolving the signal with filter coefficients
           for i in xrange(0, len(filtered_b)):
                   y_p_b = filtered_b[i]
           y_p_b=np.array(y_p_b)
        else:
            y_p_b=signal_b
        sig_b=y_p_b[0:sizet_b]
        if c.alphafilter:
           filtered_a = []
           filtered_a.append(sc.convolve(bn, signal_a)) # filter the signal by convolving the signal with filter coefficients
           for i in xrange(0, len(filtered_a)):
                   y_p_a = filtered_a[i]
           y_p_a=np.array(y_p_a)
        else:
            y_p_a=signal_a
        sig_a=y_p_a[0:sizet_a]


#-----------------------------------------------------------------------------
#   wavelets of Morlet(before)
#-----------------------------------------------------------------------------
        wt_b,WM_b,phaseb=create_wavelet(sig_b,sampling_rate,f_start,f_stop,deltafreq)
        nbptmax = (f_stop - f_start)/deltafreq
        ind=fc*nbptmax/f_stop
        phi=phaseb[ind,:]
        Longueur_phi=len(phi)
        temps_b=linspace(t0_b,t1_b,Longueur_phi)
        indice_phase=int(Longueur_phi-(abs(ti)-abs(ThresholdBeforeTMS)/(srate*1e-3)))
        v=phaseb[ind,indice_phase]
        w=WM_b[ind,indice_phase]
        reference_phi_block.append(v)
        reference_mod_block.append(w)
        phase=sc.angle(wt_b).transpose()
        sig=WM_b[ind,:]
        sup=max(sig)
        valeur_sup.append(sup)
#-----------------------------------------------------------------------------
#   somme des modules
#-----------------------------------------------------------------------------
        WSUM_b=WSUM_b+WM_b

#-----------------------------------------------------------------------------
#    wavelets of Morlet (after)
#-----------------------------------------------------------------------------
        wt_a,WM_a,phasea=create_wavelet(sig_a,sampling_rate,f_start,f_stop,deltafreq)
        nbptmax = (f_stop - f_start)/deltafreq
        ind=fc*nbptmax/f_stop
        ti_a=2.e2
        # time at which we calculate phase after TMS to organize blocks
        phi_a=phasea[ind,:]
        Longueur_phi_a=len(phi_a)
        temps_a=linspace(t0_a,t1_a,Longueur_phi_a)
        indice_phase_a=int(Longueur_phi_a-(abs(ti_a)-abs(ThresholdAfterTMS)/(srate*1e-3)))
        v_a=phasea[ind,indice_phase_a]
        w_a=WM_a[ind,indice_phase_a]
        reference_phi_block_a.append(v_a)
        reference_mod_block_a.append(w_a)
        phase_a=sc.angle(wt_a).transpose()
        sig_a=WM_b[ind,:]
        sup_a=max(sig_a)
        valeur_sup_a.append(sup_a)
#-----------------------------------------------------------------------------
#    affiche les phases de wavelet (after)
#-----------------------------------------------------------------------------
#        figure(loop+333)
#        ax1=subplot(121)
#        imb = imshow(phase,
#                                    interpolation='nearest',
#                                    extent=(t0_b, t1_b, f_start, f_stop),
#                                    origin ='lower' ,
#                                    aspect = 'normal')
#        title("WT before TMS",fontsize=9)
#        xlabel('time [s]')
#        ylabel('Freq. [Hz]')
#        ax2=subplot(122, sharey=ax1)
#        ima = imshow(phase_a,
#                                    interpolation='nearest',
#                                    extent=(t0_a, t1_a, f_start, f_stop),
#                                    origin ='lower' ,
#                                    aspect = 'normal')
#        title("WT after TMS",fontsize=9)
#        xlabel('time [s]')
#        subplots_adjust(hspace=0.05)
#        show()
#        imageName=p.imageName
#        savefig(imageName)
#        show()
#-----------------------------------------------------------------------------
#   somme des modules
#-----------------------------------------------------------------------------
        WSUM_a=WSUM_a+WM_a
    print "\n\r"
    print "fin du calcul...\n"
    print "moyenne ondelette"
    print WSUM_b[0,0:10]
    print WSUM_a[0,0:10]
#-----------------------------------------------------------------------------
#  end of calculs
#-----------------------------------------------------------------------------
    figure(4)
    subplot(221)
    plot(reference_mod_block)
    title("Amplitude at ti - not sorted",fontsize=9)
    ylabel("Modul")
    subplot(222)
    plot(reference_phi_block)
    title("Phase at ti - not sorted",fontsize=9)
    ylabel("Phase")
    xlabel("Blocks")
    reference_phi_block=np.array(reference_phi_block,dtype='float')
    reference_mod_block=np.array(reference_mod_block,dtype='float')
    valeur_sup=np.array(valeur_sup,dtype='float')

    show()
#-----------------------------------------------------------------------------
# plot of IFC before in polar coordonates of phases and amplitudes for all blocks
#-----------------------------------------------------------------------------

# radar green, solid grid lines
    rc('grid', color='#316931', linewidth=1, linestyle='-')
    rc('xtick', labelsize=15)
    rc('ytick', labelsize=15)

# force square figure and square axes looks better for polar, IMO
    width, height = matplotlib.rcParams['figure.figsize']
    sizepol = min(width, height)
        # make a square figure
#    fig = figure(figsize=(sizepol, sizepol))
    fig = figure(100)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')

    ax.plot(reference_phi_block, reference_mod_block, color='#ee8d18', marker='o',ls='none')
    maximum_mod=max(reference_mod_block)
    ax.set_rmax(maximum_mod)
    grid(True)
    ax.set_title("Voila l'ITC avant TMS!", fontsize=20)

    show()
#-----------------------------------------------------------------------------
# plot of IFC after in polar coordonates of phases and amplitudes for all blocks
#-----------------------------------------------------------------------------

# radar green, solid grid lines
    rc('grid', color='#316931', linewidth=1, linestyle='-')
    rc('xtick', labelsize=15)
    rc('ytick', labelsize=15)

# force square figure and square axes looks better for polar, IMO
    width, height = matplotlib.rcParams['figure.figsize']
    sizepol = min(width, height)
        # make a square figure
#    fig = figure(figsize=(sizepol, sizepol))
    fig = figure(101)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')

    ax.plot(reference_phi_block_a, reference_mod_block_a, color='#ee8d18', marker='o',ls='none')
    maximum_mod=max(reference_mod_block_a)
    ax.set_rmax(maximum_mod)
    grid(True)
    ax.set_title("Voila l'ITC apres TMS!", fontsize=20)

    show()
    figure(4)
#-----------------------------------------------------------------------------
#  tri des phases et des amplitudes (before)
#-----------------------------------------------------------------------------
    N=len(reference_mod_block)
    tri_mod=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    tri_phase=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    tri_sup=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    for k in range(N):
        tri_mod['indice'][k]=k
        tri_phase['indice'][k]=k
        tri_sup['indice'][k]=k
        tri_mod['valeur'][k]=reference_mod_block[k]
        tri_phase['valeur'][k]=reference_phi_block[k]
        tri_sup['valeur'][k]=valeur_sup[k]
    tri_mod=sc.sort(tri_mod,order='valeur')
    tri_phase=sc.sort(tri_phase,order='valeur')
    tri_sup=sc.sort(tri_sup,order='valeur')
    subplot(223)
    plot(tri_mod['valeur'])
    title("Amplitude at ti -  sorted",fontsize=9)
    ylabel("Modul")
    xlabel("Blocks")
    subplot(224)
    plot(tri_phase['valeur'])
    title("Phase at ti - sorted",fontsize=9)
    ylabel("Phase")
    xlabel("Blocks")
    show()
#-----------------------------------------------------------------------------
#  tri des phases et des amplitudes (after)
#-----------------------------------------------------------------------------
    figure(6)
    N=len(reference_mod_block_a)
    tri_mod_a=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    tri_phase_a=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    tri_sup_a=np.zeros(N, dtype=[ ('indice', 'i4'), ('valeur', 'f8')])
    for k in range(N):
        tri_mod_a['indice'][k]=k
        tri_phase_a['indice'][k]=k
        tri_sup_a['indice'][k]=k
        tri_mod_a['valeur'][k]=reference_mod_block_a[k]
        tri_phase_a['valeur'][k]=reference_phi_block_a[k]
        tri_sup_a['valeur'][k]=valeur_sup_a[k]
    tri_mod_a=sc.sort(tri_mod_a,order='valeur')
    tri_phase_a=sc.sort(tri_phase_a,order='valeur')
    tri_sup_a=sc.sort(tri_sup_a,order='valeur')
    subplot(223)
    plot(tri_mod_a['valeur'])
    title("Amplitude at ti_after -  sorted",fontsize=9)
    ylabel("Modul")
    xlabel("Blocks")
    subplot(224)
    plot(tri_phase_a['valeur'])
    title("Phase at ti_after - sorted",fontsize=9)
    ylabel("Phase")
    xlabel("Blocks")
    show()
#-----------------------------------------------------------------------------
#   calcul of the average over all blocs
#-----------------------------------------------------------------------------
    WSUM_b=WSUM_b/(nbblock+1.)
    WSUM_a=WSUM_a/(nbblock+1.)
#-----------------------------------------------------------------------------
#   affiche moyenne des analyses en ondelette
#-----------------------------------------------------------------------------
    figure(5)
    ax1=subplot(121)
    imb = imshow(WSUM_b,
                                    interpolation='nearest',
                                    extent=(t0_b, t1_b, f_start, f_stop),
                                    origin ='lower' ,
                                    aspect = 'normal')
    title("WT before TMS",fontsize=9)
    xlabel('time [s]')
    ylabel('Freq. [Hz]')
    ax2=subplot(122, sharey=ax1)
    ima = imshow(WSUM_a,
                                    interpolation='nearest',
                                    extent=(t0_a, t1_a, f_start, f_stop),
                                    origin ='lower' ,
                                    aspect = 'normal')
    title("WT after TMS",fontsize=9)
    xlabel('time [s]')
    subplots_adjust(hspace=0.05)
    show()
    imageName=p.imageName
    savefig(imageName)
    show()
#-----------------------------------------------------------------------------
#   affiche block (after) apres tri par amplitude
#-----------------------------------------------------------------------------
    ind=tri_mod['indice']
    m,n=M_a.shape
    figure(3)
    M_a_tri=M_a.copy()
    for k in range(n):
        M_a_tri[:,k]=M_a[:,ind[k]]
    subplot(424)
    tmin=np.min(t_a)
    tsup=np.max(t_a)
    imshow(M_a_tri.transpose(),
                            interpolation='nearest',
                            extent=(tmin,tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('After - after sorting by amplitude',fontsize=9)
    ylabel("Blocks")
#-----------------------------------------------------------------------------
#   affiche block (before) apres tri par amplitude
#-----------------------------------------------------------------------------
    ind=tri_mod['indice']
    m,n=M_b.shape
    M_b_tri=M_b.copy()
    for k in range(n):
        M_b_tri[:,k]=M_b[:,ind[k]]
    subplot(423)
    tmin=np.min(t_b)
    tsup=np.max(t_b)
    imshow(M_b_tri.transpose(),
                interpolation='nearest',
                            extent=(tmin,tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('Before - after sorting by amplitude',fontsize=9)
    ylabel("Blocks")
    show()
#-----------------------------------------------------------------------------
#   affiche block (after) apres tri par phase
#-----------------------------------------------------------------------------
    ind=tri_phase['indice']
    m,n=M_a.shape
    figure(3)
    M_a_tri=M_a.copy()
    for k in range(n):
        M_a_tri[:,k]=M_a[:,ind[k]]
    subplot(426)
    tmin=np.min(t_a)
    tsup=np.max(t_a)
    imshow(M_a_tri.transpose(),
                            interpolation='nearest',
                            extent=(tmin, tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('After - after sorting by phase',fontsize=9)
    #xlabel("Time [s]")
    ylabel("Blocks")
#-----------------------------------------------------------------------------
#   affiche block (before) apres tri par phase
#-----------------------------------------------------------------------------
    ind=tri_phase['indice']
    m,n=M_b.shape
    M_b_tri=M_b.copy()
    for k in range(n):
        M_b_tri[:,k]=M_b[:,ind[k]]
    subplot(425)
    tmin=np.min(t_b)
    tsup=np.max(t_b)
    imshow(M_b_tri.transpose(),
                            interpolation='nearest',
                            extent=(tmin, tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('Before - after sorting by phase',fontsize=9)
    #xlabel("Time [s]")
    ylabel("Blocks")
    show()

#-----------------------------------------------------------------------------
#   affiche block (before) apres tri par valeur sup
#-----------------------------------------------------------------------------
    plt.figure(3)
    ind=tri_sup['indice']
    m,n=M_b.shape
    M_b_tri=M_b.copy()
    for k in range(n):
        M_b_tri[:,k]=M_b[:,ind[k]]
    subplot(427)
    tmin=np.min(t_b)
    tsup=np.max(t_b)
    imshow(M_b_tri.transpose(),
                            interpolation='nearest',
                            extent=(tmin, tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('Before - after sorting by maximum amplitude',fontsize=9)
    xlabel("Time [s]")
    ylabel("Blocks")
    show()

#-----------------------------------------------------------------------------
#   affiche block (after) apres tri par valeur sup
#-----------------------------------------------------------------------------
    ind=tri_sup['indice']
    m,n=M_a.shape
    M_a_tri=M_a.copy()
    for k in range(n):
        M_a_tri[:,k]=M_a[:,ind[k]]
    subplot(428)
    tmin=np.min(t_a)
    tsup=np.max(t_a)
    imshow(M_a_tri.transpose(),
                            interpolation='nearest',
                            extent=(tmin, tsup, 0, n),
                            origin ='lower' ,
                            aspect = 'normal')
    title('After - after sorting by maximum amplitude',fontsize=9)
    xlabel("Time [s]")
    ylabel("Blocks")

    plt.figure(3)
    imageName=nouveau_nom + "_" +str(numv)
    plt.savefig(imageName)
    print "fin du programme"

    pp.close()
    app.exec_()
